import React from 'react';
import PropTypes from 'prop-types';
import {Card, Button, Row, Col, Form, Spin} from 'antd';
import routes from './routes';
import Return from '../common/Return';
import {FORM_OPTIONS, FORM_ROW_OPTIONS} from '../constants';
import {getDetail} from './api';
import {isYesNo} from '../Enum';
import WrappedSelect from '../common/WrappedSelect';
import TextInput from 'Shared/components/TextInput';
import RegionSelect from '../common/RegionSelect';
import {newOrUpdateOrderValidator} from './validator';
import {language, injectIntl} from './intl';
const FormItem = Form.Item;
const isYesNoList = isYesNo.toList(language);
export class NewPanel extends React.PureComponent {
    state = {
        isValidate: false,
        hasOperat: false,
        loading: false,
        data: {region: []},
    }
    componentDidMount() {
        if(this.props.id)
            this.getDetailInfo();
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok) {
                    const data = res.data;
                    data.needTransportScanning = (data.needTransportScanning === true ? 1 : 0);
                    data.isOffsiteFactory = (data.isOffsiteFactory === true ? 1 : 0);
                    const region = [];
                    if(data.areaTiledId)
                        region.push(data.areaTiledId);
                    if(data.countryId)
                        region.push(data.countryId);
                    if(data.provinceId)
                        region.push(data.provinceId);
                    if(data.cityId)
                        region.push(data.cityId);
                    data.region = region;
                    this.setState({
                        loading: false,
                        data: res.data
                    });
                } else
                    this.setState({
                        loading: false
                    });
            });
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onSubmit = () => {
        const data = this.state.data;
        const isValid = newOrUpdateOrderValidator(data);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        this.props.onSubmit(data).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    };
    onClickReturnBtn = () => {
        this.props.onCancel();
    }
    render() {
        const {data} = this.state;
        const {formatMessage} = this.props.intl;
        const {brands} = this.props.initEnumData;
        const validateBrandId = !data.brandId && this.state.validate ? 'error' : null;
        const validateCode = !data.code && this.state.validate ? 'error' : null;
        const validateName = !data.name && this.state.validate ? 'error' : null;
        const validateRegionId = !(data.region.length > 0) && this.state.validate ? 'error' : null;
        const validateAddress = !data.address && this.state.validate ? 'error' : null;
        const validateContactNumber = !data.contactNumber && this.state.validate ? 'error' : null;
        const validateFax = !data.fax && this.state.validate ? 'error' : null;
        const regionSelectDefaultOption = {
            areaTiledId: data.areaTiledId,
            areaName: data.areaName,
            countryId: data.countryId,
            countryName: data.countryName,
            provinceId: data.provinceId,
            provinceName: data.provinceName,
            cityId: data.cityId,
            cityName: data.cityName
        };
        return (
            <div>
                <Spin spinning={this.state.loading}>
                    <Form className="form-standard">
                        <Card title={formatMessage({
                            id: 'addPanel.card.title',
                            defaultMessage: '基本信息'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}><FormItem label={formatMessage({
                                    id: 'newPanel.form.brandId',
                                    defaultMessage: '品牌'
                                })}{...FORM_OPTIONS.item}
                                validateStatus={validateBrandId}
                                required>
                                    <WrappedSelect
                                        allowClear
                                        name="brandId"
                                        value={data.brandId}
                                        options={brands}
                                        onChange={this.onChange}/>
                                </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.text.code',
                                        defaultMessage: '生产工厂编号'
                                    })}{...FORM_OPTIONS.item}
                                    validateStatus={validateCode}
                                    required>
                                        <TextInput
                                            name="code"
                                            value={data.code}
                                            onBlur={this.onChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.text.name',
                                        defaultMessage: '生产工厂名称'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateName}
                                    required>
                                        <TextInput
                                            name="name"
                                            value={data.name}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.regionId',
                                        defaultMessage: '国省市'
                                    })}{...FORM_OPTIONS.item}
                                    validateStatus={validateRegionId}
                                    required>
                                        <RegionSelect
                                            name="region"
                                            defaultOption={regionSelectDefaultOption}
                                            value={data.region}
                                            onChange={this.onChange}
                                            changeOnSelect={true} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.text.address',
                                        defaultMessage: '地址'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateAddress}
                                    required>
                                        <TextInput
                                            name="address"
                                            value={data.address}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.text.contactNumber',
                                        defaultMessage: '电话'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateContactNumber}
                                    required>
                                        <TextInput
                                            name="contactNumber"
                                            value={data.contactNumber}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.text.fax',
                                        defaultMessage: '传真'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateFax}
                                    required>
                                        <TextInput
                                            name="fax"
                                            value={data.fax}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.text.needTransportScanning',
                                        defaultMessage: '是否驳运扫描'
                                    })} {...FORM_OPTIONS.item}>
                                        {this.props.id ? <WrappedSelect
                                            allowClear
                                            id="needTransportScanning"
                                            options={isYesNoList}
                                            value={data.needTransportScanning === null ? null : data.needTransportScanning}
                                            onChange={this.onChange} />
                                            : <WrappedSelect
                                                allowClear
                                                id="needTransportScanning"
                                                options={isYesNoList}
                                                value={data.needTransportScanning}
                                                onChange={this.onChange} />
                                        }
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.text.isOffsiteFactory',
                                        defaultMessage: '是否异地工厂'
                                    })} {...FORM_OPTIONS.item}>
                                        {this.props.id ? <WrappedSelect
                                            allowClear
                                            id="isOffsiteFactory"
                                            options={isYesNoList}
                                            value={data.isOffsiteFactory === null ? null : data.isOffsiteFactory}
                                            onChange={this.onChange} />
                                            : <WrappedSelect
                                                allowClear
                                                id="isOffsiteFactory"
                                                options={isYesNoList}
                                                value={data.isOffsiteFactory}
                                                onChange={this.onChange} />
                                        }
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row className="row-margin">
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.text.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        <TextInput
                                            type="textarea"
                                            name="remark"
                                            value={data.remark}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                    </Form>
                    <Card>
                        <Row>
                            <Col className="col-align-right">
                                <Button key="audit"
                                    onClick={this.onSubmit}
                                    type="primary"
                                    loading={this.state.loading}>
                                    {formatMessage({
                                        id: 'newPanel.btn.submit',
                                        defaultMessage: '保存'
                                    })}</Button>
                            </Col>
                        </Row>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {tableSearch, onSubmit} from './actions';
import {createSelector} from 'reselect';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `(${item.code})${item.name}`,
            value: item.id
        })) : [];
        return {
            brands
        };
    }
);
const mapStateToProps = state => ({
    initEnumData: getinitEnumData(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: data => dispatch(onSubmit(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
